<template>
	<view class="container">
		<tech-nav-bar title="忙时" :currentPage="'/pages/technician/time'"></tech-nav-bar>
		<!-- 日期选择栏 -->
		<scroll-view class="date-scroll" scroll-x>
			<view class="date-list">
				<view v-for="(date, index) in dateList" :key="index" class="date-item"
					:class="{ 'active': isDateSelected(date.date) }" @tap="selectDate(date)">
					<text class="date-code">{{ date.text }}</text>
					<text class="date-text">{{ date.code }}</text>
				</view>
			</view>
		</scroll-view>
		<!-- 服务时间设置 -->
		<view class="service-time">
			<view class="time-header">
				<text>服务时段：</text>
				<text class="time-range">{{ timeRangeText() }}</text>
				<!-- <text class="modify" @tap="modifyTimeRange">修改 ></text> -->
				<!-- <view class="batch-setting-btn" @tap="showBatchSetting">
					批量设置
				</view> -->
			</view>
			<view class="time-grid">
				<view v-for="(time, index) in timeSlots" :key="index" class="time-item" :class="{
					'selected': isTimeSelected(time),
					'busy': isBusyTime(time),
					'past': isPastTime(time),
					'rest': isRest()
				  }" @tap="onTimeSlotClick(time)">
					<text class="time">{{ time }}</text>
					<text class="status">{{ getTimeStatus(time) }}</text>
				</view>
			</view>
		</view>
		<!-- 底部保存按钮 -->
		<!-- <view class="save-button-container">
			<button class="save-button" @tap="saveTimeSlots">设为忙时</button>
		</view> -->
		<!-- 时间选择弹窗 -->
		<view class="custom-popup" v-if="showPopup">
			<view class="popup-mask" @tap="cancelSelect"></view>
			<view class="popup-content">
				<view class="time-popup">
					<view class="close-icon" @tap="cancelSelect">×</view>
					<view class="time-selector">
						<!-- 开始时间选择器 -->
						<picker-view :value="startTimePickerValue" @change="onStartTimeChange" class="time-picker-view"
							indicator-style="height: 100rpx;" :mask-style="maskStyle">
							<picker-view-column>
								<view class="picker-item" v-for="hour in hours" :key="hour">
									{{ hour.padStart(2, '0') }}
								</view>
							</picker-view-column>
							<picker-view-column style="width: 50rpx;">
								<view class="picker-separator">:</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="minute in halfHourMinutes" :key="minute">
									{{ minute }}
								</view>
							</picker-view-column>
						</picker-view>
						<!-- 结束时间选择器 -->
						<picker-view :value="endTimePickerValue" @change="onEndTimeChange" class="time-picker-view"
							indicator-style="height: 100rpx;" :mask-style="maskStyle">
							<picker-view-column>
								<view class="picker-item" v-for="hour in hours" :key="hour">
									{{ hour.padStart(2, '0') }}
								</view>
							</picker-view-column>
							<picker-view-column style="width: 50rpx;">
								<view class="picker-separator">:</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="minute in halfHourMinutes" :key="minute">
									{{ minute }}
								</view>
							</picker-view-column>
						</picker-view>
					</view>
					<view class="confirm-btn" @tap="confirmSelect">
						确定
					</view>
				</view>
			</view>
		</view>
		<!-- 批量设置弹窗 -->
		<view class="custom-popup" v-if="showBatchPopup">
			<view class="popup-mask" @tap="cancelBatchSetting"></view>
			<view class="popup-content">
				<view class="batch-popup">
					<view class="batch-popup-title">
						批量设置忙时/闲时
						<text class="close-icon" @tap="cancelBatchSetting">×</text>
					</view>
					<!-- 时间范围显示 -->
					<view class="time-range-display">
						<view class="time-input" @tap="showStartTimeSelect">{{ formatBatchDate(batchStartDate) }}
							{{ batchStartTime }}
						</view>
						<view class="time-separator">—</view>
						<view class="time-input" @tap="showEndTimeSelect">{{ formatBatchDate(batchEndDate) }}
							{{ batchEndTime }}
						</view>
					</view>
					<!-- 日期选择按钮组 -->
					<view class="date-buttons">
						<view class="date-button" :class="{ 'active': batchDateType === 'future24' }"
							@tap="selectBatchDateType('future24')">
							未来24时
						</view>
						<view class="date-button" :class="{ 'active': batchDateType === 'today' }"
							@tap="selectBatchDateType('today')">
							今天
						</view>
						<view class="date-button" :class="{ 'active': batchDateType === 'tomorrow' }"
							@tap="selectBatchDateType('tomorrow')">
							明天
						</view>
						<view class="date-button" :class="{ 'active': batchDateType === 'afterTomorrow' }"
							@tap="selectBatchDateType('afterTomorrow')">
							后天
						</view>
					</view>
					<!-- 操作按钮 -->
					<view class="batch-action-buttons">
						<view class="batch-action-btn available" @tap="setBatchAvailable">
							设为可约
						</view>
						<view class="batch-action-btn busy" @tap="setBatchBusy">
							设为忙时
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 批量设置开始时间选择弹窗 -->
		<view class="custom-popup" v-if="showBatchStartPopup">
			<view class="popup-mask" @tap="cancelBatchTimeSelect"></view>
			<view class="popup-content">
				<view class="time-popup">
					<view class="close-icon" @tap="cancelBatchTimeSelect">×</view>
					<!-- 日期选择部分 -->
					<scroll-view class="date-selector" scroll-y>
						<view class="date-row" v-for="(date, index) in batchDateOptions" :key="index"
							:class="{ 'active': isBatchDateSelected(date.date) }"
							@tap="selectBatchDate(date.date, 'start')">
							<text class="date-code">{{ date.text }}</text>
							<text class="date-text">{{ formatDate(date.date) }}</text>
						</view>
					</scroll-view>
					<view class="time-selector">
						<!-- 开始时间选择器 -->
						<picker-view :value="batchStartTimePickerValue" @change="onBatchStartTimeChange"
							class="time-picker-view" indicator-style="height: 100rpx;" :mask-style="maskStyle">
							<picker-view-column>
								<view class="picker-item" v-for="hour in hours" :key="hour">
									{{ hour.padStart(2, '0') }}
								</view>
							</picker-view-column>
							<picker-view-column style="width: 50rpx;">
								<view class="picker-separator">:</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="minute in halfHourMinutes" :key="minute">
									{{ minute }}
								</view>
							</picker-view-column>
						</picker-view>
					</view>
					<view class="confirm-btn" @tap="confirmBatchStartTimeSelect">
						确定
					</view>
				</view>
			</view>
		</view>
		<!-- 批量设置结束时间选择弹窗 -->
		<view class="custom-popup" v-if="showBatchEndPopup">
			<view class="popup-mask" @tap="cancelBatchTimeSelect"></view>
			<view class="popup-content">
				<view class="time-popup">
					<view class="close-icon" @tap="cancelBatchTimeSelect">×</view>
					<!-- 日期选择部分 -->
					<scroll-view class="date-selector" scroll-y>
						<view class="date-row" v-for="(date, index) in batchDateOptions" :key="index"
							:class="{ 'active': isBatchDateSelected(date.date) }"
							@tap="selectBatchDate(date.date, 'end')">
							<text class="date-code">{{ date.text }}</text>
							<text class="date-text">{{ formatDate(date.date) }}</text>
						</view>
					</scroll-view>
					<view class="time-selector">
						<!-- 结束时间选择器 -->
						<picker-view :value="batchEndTimePickerValue" @change="onBatchEndTimeChange"
							class="time-picker-view" indicator-style="height: 100rpx;" :mask-style="maskStyle">
							<picker-view-column>
								<view class="picker-item" v-for="hour in hours" :key="hour">
									{{ hour.padStart(2, '0') }}
								</view>
							</picker-view-column>
							<picker-view-column style="width: 50rpx;">
								<view class="picker-separator">:</view>
							</picker-view-column>
							<picker-view-column>
								<view class="picker-item" v-for="minute in halfHourMinutes" :key="minute">
									{{ minute }}
								</view>
							</picker-view-column>
						</picker-view>
					</view>
					<view class="confirm-btn" @tap="confirmBatchEndTimeSelect">
						确定
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import TechNavBar from '@/components/tech-nav-bar.vue';
	import {
		request
	} from '@/utils/request.js'

	export default {
		components: {
			TechNavBar
		},
		data() {
			return {
				rest: false,
				workDays: [],
				dateList: [],
				selectedDate: new Date(),
				timeSlots: [],
				selectedTimeSlots: [],
				busyTimeSlots: [],
				techId: '',
				apiTimeSlots: [], // 存储从API获取的时间段
				type: 'start',
				// 添加时间选择弹窗相关数据
				showPopup: false,
				workTime: {
					start: '',
					end: ''
				},
				tempTime: {
					start: '08:00',
					end: '22:00'
				},
				hours: Array.from({
					length: 15
				}, (_, i) => String(i + 8)), // 从8点到22点
				halfHourMinutes: ['00', '30'],
				startTimePickerValue: [0, 0, 0], // 8点对应索引0
				endTimePickerValue: [14, 0, 0], // 22点对应索引14
				maskStyle: 'background-image: linear-gradient(180deg, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.6)), linear-gradient(0deg, rgba(255, 255, 255, 0.95), rgba(255, 255, 255, 0.6));',
				// 批量设置相关数据
				showBatchPopup: false,
				batchStartDate: new Date(),
				batchEndDate: new Date(),
				batchStartTime: '11:00',
				batchEndTime: '23:00',
				batchDateType: 'today', // future24, today, tomorrow, afterTomorrow
				dateRowActive: 0,
				serviceTimeInfo: null,
				// 批量设置时间选择弹窗
				showBatchStartPopup: false,
				showBatchEndPopup: false,
				batchStartTimePickerValue: [3, 0, 0], // 默认11:00
				batchEndTimePickerValue: [14, 0, 1], // 默认22:30
				batchDateOptions: [{
						text: '今天',
						date: new Date()
					},
					{
						text: '明天',
						date: null
					},
					{
						text: '后天',
						date: null
					}
				],
				tempBatchStartDate: new Date(),
				tempBatchEndDate: new Date(),
				tempBatchStartTime: '11:00',
				tempBatchEndTime: '23:00',
			}
		},
		/*onLoad() {
			// 从本地缓存加载工作时间范围（如果有）
			const savedWorkTime = uni.getStorageSync('techWorkTime')
			if (savedWorkTime) {
				const workTime = JSON.parse(savedWorkTime)
				// 确保工作时间在8:00-22:00范围内
				const [startHour, startMinute] = workTime.start.split(':').map(Number)
				const [endHour, endMinute] = workTime.end.split(':').map(Number)
				// 限制开始时间不早于8:00
				let validStartHour = Math.max(8, startHour)
				let validStartMinute = startHour < 8 ? 0 : startMinute
				// 限制结束时间不晚于22:00
				let validEndHour = Math.min(22, endHour)
				let validEndMinute = endHour > 22 ? 0 : endMinute
				this.workTime = {
					start: `${String(validStartHour).padStart(2, '0')}:${String(validStartMinute).padStart(2, '0')}`,
					end: `${String(validEndHour).padStart(2, '0')}:${String(validEndMinute).padStart(2, '0')}`
				}
				// 更新临时时间
				this.tempTime = {
					...this.workTime
				}
				// 更新时间选择器的值
				// 调整分钟到最接近的半小时值(0或30)
				const startMinuteIndex = validStartMinute < 15 ? 0 : (validStartMinute < 45 ? 1 : 0)
				const endMinuteIndex = validEndMinute < 15 ? 0 : (validEndMinute < 45 ? 1 : 0)
				// 调整小时索引，因为hours数组从8开始
				this.startTimePickerValue = [
					Math.max(0, Math.min(this.hours.length - 1, validStartHour - 8)),
					0,
					startMinuteIndex
				]
				this.endTimePickerValue = [
					Math.max(0, Math.min(this.hours.length - 1, validEndHour - 8)),
					0,
					endMinuteIndex
				]
			}
			// 获取技师ID
			const userInfo = uni.getStorageSync('userInfo')
			this.techId = userInfo ? userInfo.techId || '' : ''
			// 初始化时间槽
			this.timeSlots = this.generateTimeSlots(this.workTime.start, this.workTime.end)
			// 加载时间段数据
			this.loadTimeSlots()

		},*/
		async created() {
			const userInfo = uni.getStorageSync("userInfo")
			this.techId = userInfo.techId
			const res = await request({
				url: `${uni.$config.baseUrl}/schedule/schedule/listAll?technicianId=${userInfo.techId}`,
				method: 'GET',
			});
			if (!res.rows) {
				uni.showToast({
					title: '请设置接单时段',
					icon: 'error',
					duration: 2000
				})
				return
			} else {
				this.workTime = {
					start: res.rows[0].startTime,
					end: res.rows[0].endTime
				};
				this.workDays = res.rows[0].workDays.split(',')
				this.initDateList()
				this.initTimeSlots(res.rows[0].startTime, res.rows[0].endTime)
				// 获取技师服务时间点
				this.getTechnicianServiceTimePoint(userInfo.techId)
			}
		},
		methods: {
			isRest() {
				return this.rest
			},
			selectDate(date) {
				this.selectedDate = date.date
				this.initTimeSlots(this.workTime.start, this.workTime.end)
				this.getTechnicianServiceTimePoint(this.techId)
			},
			// 获取技师服务时间点
			async getTechnicianServiceTimePoint(techId) {
				const res = await request({
					url: `${uni.$config.baseUrl}/servicetime/servicetime/listAll?techId=${techId}&serviceDate=${this.formatFullDate(this.selectedDate)}`,
					method: 'GET'
				})
				if (this.workDays && !this.workDays.includes(
						(this.selectedDate.getDay() === 0 ? 7 : this.selectedDate.getDay()).toString()
					)) {
					this.rest = true
					this.selectedTimeSlots = []
					this.busyTimeSlots = []
				} else {
					this.rest = false
					if (res.rows.length > 0) {
						console.log(res.rows)
						this.selectedTimeSlots = res.rows && res.rows[0].serviceDuration ? res.rows[0].serviceDuration
							.split(',') : []
						this.busyTimeSlots = res.rows && res.rows[0].servicedDuration ? res.rows[0].servicedDuration.split(
							',') : []
					} else {
						// 未查询到任何服务时段信息，清空本地显示，避免上一天的数据残留
						this.selectedTimeSlots = []
						this.busyTimeSlots = []
					}
				}
			},
			initTimeSlots(start, end) {
				// 解析开始时间和结束时间
				const [startHours, startMinutes] = start.split(':').map(Number);
				const [endHours, endMinutes] = end.split(':').map(Number);
				// 计算开始时间和结束时间的分钟数
				let currentMinutes = startHours * 60 + startMinutes;
				const endMinutesTotal = endHours * 60 + endMinutes;
				this.timeSlots = []
				while (currentMinutes <= endMinutesTotal) {
					this.timeSlots.push(
						`${Math.floor(currentMinutes / 60).toString().padStart(2, '0')}:${(currentMinutes % 60).toString().padStart(2, '0')}`
					);
					// 移动到下一个时间点（增加30分钟）
					currentMinutes += 30;
				}
			},
			initDateList() {
				const MAX_DAYS = 4; // 今天+3天
				this.dateList = Array.from({
					length: MAX_DAYS
				}, (_, index) => {
					const date = new Date()
					date.setDate(date.getDate() + index)
					let text = index === 0 ? '今天' : index === 1 ? '明天' : index === 2 ? '后天' : this.formatDateMonth(
						date)
					return {
						code: `${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
						text: text,
						date: date
					}
				})
			},
			// 格式化日期为 MM-DD 格式
			formatDate(date) {
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${month}-${day}`
			},
			// 格式化日期为 "X月X日 周X" 格式
			formatDateMonth(date) {
				const month = date.getMonth() + 1
				const day = date.getDate()
				const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
				return `${month}月${day}日 ${weekDay}`
			},
			// 生成时间段
			generateTimeSlots(startTime = '08:00', endTime = '22:00') {
				const slots = []
				const [startHour, startMinute] = startTime.split(':').map(Number)
				const [endHour, endMinute] = endTime.split(':').map(Number)
				// 确保开始时间不早于8:00
				let hour = Math.max(8, startHour)
				let minute = startHour < 8 ? 0 : startMinute
				// 循环直到结束时间，不超过22:00
				const maxHour = Math.min(22, endHour)
				const maxMinute = endHour > 22 ? 0 : endMinute
				while (hour < maxHour || (hour === maxHour && minute <= maxMinute)) {
					slots.push(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`)
					// 增加30分钟
					minute += 30
					if (minute >= 60) {
						hour += 1
						minute = 0
					}
				}
				return slots
			},
			// 获取未来日期
			getNextDay(days) {
				const date = new Date()
				date.setDate(date.getDate() + days)
				return date
			},
			// 是否选中日期
			isDateSelected(date) {
				return this.formatDate(date) === this.formatDate(this.selectedDate)
			},
			// 时间槽点击事件
			onTimeSlotClick(time) {
				if (this.rest) {
					return
				}
				// 如果是过去的时间，不允许选择
				if (this.isPastTime(time)) {
					uni.showToast({
						title: '无法选择过去的时间',
						icon: 'none'
					})
					return
				}
				// 如果是忙碌时间，提示已被预约
				if (this.busyTimeSlots.includes(time)) {
					uni.showToast({
						title: '该时段已被预约',
						icon: 'none'
					})
					return
				}
				// 切换选择状态
				const index = this.selectedTimeSlots.indexOf(time)
				if (index > -1) {
					// 如果已选择，则取消选择
					this.selectedTimeSlots.splice(index, 1)
				} else {
					// 如果未选择，则添加到选择列表
					this.selectedTimeSlots.push(time)
				}
				// 如果有serviceTimeInfo，更新serviceDuration
				if (this.serviceTimeInfo) {
					// 创建serviceDuration的副本以防止直接修改引用
					const updatedServiceTimeInfo = {
						...this.serviceTimeInfo
					}
					// 将选中的时间段更新到serviceDuration
					updatedServiceTimeInfo.serviceDuration = this.selectedTimeSlots.join(',')
					// 调用更新API
					this.updateServiceTime(updatedServiceTimeInfo)
				} else {
					this.saveWorkTimeToServer()
				}
			},
			// 更新技师服务时段
			updateServiceTime(serviceTimeInfo) {
				// 将selectedDate转为yyyy-MM-dd格式
				const formattedDate = this.formatFullDate(this.selectedDate)
				serviceTimeInfo.serviceDate = formattedDate
				serviceTimeInfo.startTime = this.workTime.start
				serviceTimeInfo.endTime = this.workTime.end
				if (!this.techId) {
					console.error('技师ID不存在')
					return
				}

				// 请求更新技师服务时段
				uni.request({
					url: `${uni.$config.baseUrl}/servicetime/servicetime`,
					method: 'PUT',
					data: serviceTimeInfo,
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						if (res.data && res.data.code === 200) {
							console.log('服务时段更新成功:', res.data)
							const date = this.formatFullDate(this.selectedDate)
							this.getServiceTimeSlots(date)
						} else {
							console.error('服务时段更新失败:', res.data.msg)
							uni.showToast({
								title: '设置失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('服务时段更新请求失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},

			// 是否选中时间段
			isTimeSelected(time) {
				return this.selectedTimeSlots.includes(time)
			},

			// 是否是忙碌时间
			isBusyTime(time) {
				// 检查是否在忙碌时间列表中
				if (this.busyTimeSlots != [] && this.busyTimeSlots.includes(time)) {
					return true;
				}
				return false;
			},

			// 获取时间段状态文本
			getTimeStatus(time) {
				if (this.rest) {
					return '休息'
				}
				if (this.isPastTime(time)) {
					return '已过期'
				}
				if (this.busyTimeSlots.includes(time)) {
					return '被约'
				}
				if (this.selectedTimeSlots.includes(time)) {
					return '忙时'
				}
				return '可约'
			},

			// 修改服务时间范围
			modifyTimeRange() {
				// 初始化临时时间为当前工作时间
				this.tempTime = {
					start: this.workTime.start,
					end: this.workTime.end
				}

				// 确保值被正确初始化
				const [startHour, startMinute] = this.workTime.start.split(':').map(Number)
				const [endHour, endMinute] = this.workTime.end.split(':').map(Number)

				// 调整分钟到最接近的半小时值(0或30)
				const startMinuteIndex = startMinute < 15 ? 0 : (startMinute < 45 ? 1 : 0)
				const endMinuteIndex = endMinute < 15 ? 0 : (endMinute < 45 ? 1 : 0)

				// 调整小时索引，因为hours数组从8开始
				this.startTimePickerValue = [
					Math.max(0, Math.min(this.hours.length - 1, startHour - 8)),
					0,
					startMinuteIndex
				]

				this.endTimePickerValue = [
					Math.max(0, Math.min(this.hours.length - 1, endHour - 8)),
					0,
					endMinuteIndex
				]

				// 显示时间选择弹窗
				this.showPopup = true
			},

			// 开始时间改变事件
			onStartTimeChange(e) {
				const values = e.detail.value
				const hour = this.hours[values[0]]
				const minute = this.halfHourMinutes[values[2]]

				this.tempTime.start = `${hour}:${minute}`
				console.log('开始时间改变:', this.tempTime.start)
			},

			// 结束时间改变事件
			onEndTimeChange(e) {
				const values = e.detail.value
				const hour = this.hours[values[0]]
				const minute = this.halfHourMinutes[values[2]]

				this.tempTime.end = `${hour}:${minute}`
				console.log('结束时间改变:', this.tempTime.end)
			},

			// 取消时间选择
			cancelSelect() {
				this.showPopup = false
			},

			// 确认时间选择
			confirmSelect() {
				if (this.tempTime.start && this.tempTime.end) {
					this.workTime = {
						...this.tempTime
					}
				}

				// 重新生成时间槽
				this.timeSlots = this.generateTimeSlots(this.workTime.start, this.workTime.end)

				// 保存到本地缓存
				uni.setStorageSync('techWorkTime', JSON.stringify(this.workTime))

				// 调用API保存到服务器
				this.saveWorkTimeToServer()

				// 关闭弹窗
				this.showPopup = false

				// 提示更新成功
				uni.showToast({
					title: '时间范围已更新',
					icon: 'success'
				})
			},

			// 保存工作时间到服务器
			saveWorkTimeToServer() {
				if (!this.techId) {
					console.error('技师ID不存在')
					return
				}

				const date = this.formatFullDate(this.selectedDate)

				// 确保小时是两位数格式
				const [startHour, startMinute] = this.workTime.start.split(':').map(Number)
				const [endHour, endMinute] = this.workTime.end.split(':').map(Number)

				const formattedStartTime = `${String(startHour).padStart(2, '0')}:${String(startMinute).padStart(2, '0')}`
				const formattedEndTime = `${String(endHour).padStart(2, '0')}:${String(endMinute).padStart(2, '0')}`

				// 构建请求数据
				const data = {
					techId: this.techId,
					serviceDate: date,
					serviceDuration: this.selectedTimeSlots.join(','),
					startTime: this.workTime.start, // 使用标准ISO格式 HH:mm
					endTime: this.workTime.end, // 使用标准ISO格式 HH:mm
					status: '0' // 假设0表示可约状态
				}

				// 请求保存技师服务时间
				uni.request({
					url: `${uni.$config.baseUrl}/servicetime/servicetime`,
					method: 'POST',
					data: data,
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						if (res.data && res.data.code === 200) {
							console.log('工作时间保存成功')
							// 重新加载时间段数据
							this.loadTimeSlots()
						} else {
							console.error('工作时间保存失败:', res.data.msg)
							uni.showToast({
								title: '工作时间保存失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('工作时间保存请求失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},

			// 格式化日期为 MM-DD 格式
			formatDate(date) {
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${month}-${day}`
			},

			// 格式化日期为 yyyy-MM-dd 格式 (API需要)
			formatFullDate(date) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},

			// 加载时间段数据
			loadTimeSlots() {
				if (!this.techId) {
					console.error('技师ID不存在')
					return
				}

				const date = this.formatFullDate(this.selectedDate)

				// 先尝试获取技师服务时间
				this.getServiceTimeSlots(date)
			},

			// 获取技师服务时间
			getServiceTimeSlots(date) {
				// this.selectedTimeSlots = []   // 保留当前已选，避免闪烁
				// 保持现有忙碌状态，等接口返回再更新，减少闪烁
				uni.showLoading({
					title: '加载中...'
				})

				// 请求技师服务时间
				uni.request({
					url: `${uni.$config.baseUrl}/servicetime/servicetime/listAll`,
					method: 'GET',
					data: {
						techId: this.techId,
						serviceDate: date
					},
					success: (res) => {
						uni.hideLoading()

						if (res.data && res.data.code === 200 && res.data.rows && res.data.rows.length > 0) {
							// 处理返回的时间段数据
							this.serviceTimeInfo = res.data.rows[0]
							if (res.data.rows[0].serviceDuration && res.data.rows[0].serviceDuration.split(',')
								.length > 0) {
								this.selectedTimeSlots = res.data.rows[0].serviceDuration.split(',')
							} else if (res.data.rows[0].serviceDuration == null) {
								this.selectedTimeSlots = []
							} else {
								this.selectedTimeSlots = [res.data.rows[0].serviceDuration]
							}

							if (res.data.rows[0].servicedDuration && res.data.rows[0].servicedDuration.split(
									',').length > 0) {
								console.log('技师服务时间:', res.data.rows[0].servicedDuration)
								this.busyTimeSlots = res.data.rows[0].servicedDuration.split(',')
								console.log('技师服务时间1:', this.busyTimeSlots)
							} else if (res.data.rows[0].servicedDuration == null) {
								this.busyTimeSlots = []
							} else {
								this.busyTimeSlots = [res.data.rows[0].servicedDuration]
							}
							// console.log('技师服务时间:',this.selectedTimeSlots)
							console.log('技师忙碌时间:', this.busyTimeSlots)

							this.processTimeSlots(res.data.rows)
						} else {
							// 如果没有结果，尝试获取技师工作时间
							this.getWorkSchedule(date)
						}
					},
					fail: (err) => {
						uni.hideLoading()
						console.error('获取技师服务时间失败:', err)
						// 如果请求失败，尝试获取技师工作时间
						this.getWorkSchedule(date)
					}
				})
			},

			// 获取技师工作时间
			getWorkSchedule(date) {
				this.busyTimeSlots = []
				uni.showLoading({
					title: '加载中...'
				})

				// 请求技师工作时间
				uni.request({
					url: `${uni.$config.baseUrl}/schedule/schedule/listAll`,
					method: 'GET',
					data: {
						technicianId: this.techId,
						date: date
					},
					success: (res) => {
						uni.hideLoading()

						if (res.data && res.data.code === 200 && res.data.rows && res.data.rows.length > 0) {
							// 处理返回的工作时间数据
							this.processWorkSchedule(res.data.rows)
						} else {
							console.log('没有找到技师工作时间数据')
							// 使用默认时间段
						}
					},
					fail: (err) => {
						uni.hideLoading()
						console.error('获取技师工作时间失败:', err)
					}
				})
			},

			// 处理技师服务时间数据
			processTimeSlots(data) {
				this.apiTimeSlots = []

				data.forEach(item => {
					if (item.startTime && item.endTime) {
						// 解析开始和结束时间
						const startTimeStr = item.startTime.substring(0, 5) // 取HH:mm格式
						const endTimeStr = item.endTime.substring(0, 5) // 取HH:mm格式

						// 将这个时间段的所有30分钟时间槽添加到apiTimeSlots
						this.apiTimeSlots = this.apiTimeSlots.concat(
							this.generateTimeSlotsBetween(startTimeStr, endTimeStr)
						)

						// // 如果状态表示忙碌，也添加到busyTimeSlots
						// if (item.status === '1' || item.status === 1) { // 假设1表示忙碌
						//   this.busyTimeSlots = this.busyTimeSlots.concat(
						//     this.generateTimeSlotsBetween(startTimeStr, endTimeStr)
						//   )
						//   console.log('技师忙碌时间2:',this.busyTimeSlots)
						// }
					}
				})

				// 如果API返回的时间段不为空，用它替换默认的时间段
				if (this.apiTimeSlots.length > 0) {
					// 去重
					this.apiTimeSlots = [...new Set(this.apiTimeSlots)]
					this.busyTimeSlots = [...new Set(this.busyTimeSlots)]

					// 排序，保证时间段升序，workTime 正常
					this.apiTimeSlots.sort((a, b) => {
						const [ah, am] = a.split(':').map(Number)
						const [bh, bm] = b.split(':').map(Number)
						return ah * 60 + am - (bh * 60 + bm)
					})

					// 更新workTime以匹配API返回的时间范围
					if (this.apiTimeSlots.length > 0) {
						this.workTime = {
							start: this.apiTimeSlots[0],
							end: this.apiTimeSlots[this.apiTimeSlots.length - 1]
						}

						// 重新生成时间槽
						this.timeSlots = this.generateTimeSlots(this.workTime.start, this.workTime.end)
					}
				}
			},

			// 处理技师工作时间数据
			processWorkSchedule(data) {
				if (data.length > 0) {
					const item = data[0]

					if (item.startTime && item.endTime) {
						// 解析开始和结束时间
						const startTimeStr = item.startTime.substring(0, 5) // 取HH:mm格式
						const endTimeStr = item.endTime.substring(0, 5) // 取HH:mm格式

						// 更新工作时间
						this.workTime = {
							start: startTimeStr,
							end: endTimeStr
						}

						// 重新生成时间槽
						this.timeSlots = this.generateTimeSlots(this.workTime.start, this.workTime.end)
					}
				}
			},

			// 生成指定开始和结束时间之间的所有30分钟时间槽
			generateTimeSlotsBetween(startTime, endTime) {
				const slots = []
				const [startHour, startMinute] = startTime.split(':').map(Number)
				const [endHour, endMinute] = endTime.split(':').map(Number)

				// 确保开始时间不早于8:00
				let hour = Math.max(8, startHour)
				let minute = startHour < 8 ? 0 : startMinute

				// 循环直到结束时间，不超过22:00
				const maxHour = Math.min(22, endHour)
				const maxMinute = endHour > 22 ? 0 : endMinute

				while (hour < maxHour || (hour === maxHour && minute <= maxMinute)) {
					slots.push(`${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`)

					// 增加30分钟
					minute += 30
					if (minute >= 60) {
						hour += 1
						minute = 0
					}
				}

				return slots
			},

			// 页面跳转方法
			goToHome() {
				uni.navigateTo({
					url: '/pages/technician/home'
				})
			},
			goToOrder() {
				uni.navigateTo({
					url: '/pages/technician/order'
				})
			},
			goToMessage() {
				uni.navigateTo({
					url: '/pages/technician/message'
				})
			},
			goToMine() {
				uni.navigateTo({
					url: '/pages/technician/my'
				})
			},
			// 修改服务时间范围的时间标题显示
			timeRangeText() {
				return `${this.workTime.start}-${this.workTime.end}`
			},

			// 保存选择的时间槽
			saveTimeSlots() {
				if (this.selectedTimeSlots.length === 0) {
					uni.showToast({
						title: '请至少选择一个时间段',
						icon: 'none'
					})
					return
				}

				// 如果有serviceTimeInfo，直接更新
				if (this.serviceTimeInfo) {
					const updatedServiceTimeInfo = {
						...this.serviceTimeInfo
					}
					updatedServiceTimeInfo.serviceDuration = this.selectedTimeSlots.join(',')
					updatedServiceTimeInfo.status = '1' // 设置为忙时状态

					// 调用更新API
					uni.request({
						url: `${uni.$config.baseUrl}/schedule/schedule`,
						method: 'PUT',
						data: updatedServiceTimeInfo,
						header: {
							'Content-Type': 'application/json'
						},
						success: (res) => {
							if (res.data && res.data.code === 200) {
								console.log('忙时设置成功')

								// 更新本地状态
								for (const time of this.selectedTimeSlots) {
									if (!this.busyTimeSlots.includes(time)) {
										this.busyTimeSlots.push(time)
									}
								}

								// 清空选择的时间槽
								this.selectedTimeSlots = []

								uni.showToast({
									title: '已设置为忙时',
									icon: 'success'
								})

								// 重新加载时间段数据
								this.loadTimeSlots()
							} else {
								console.error('忙时设置失败:', res.data.msg)
								uni.showToast({
									title: '设置失败',
									icon: 'none'
								})
							}
						},
						fail: (err) => {
							console.error('忙时设置请求失败:', err)
							uni.showToast({
								title: '网络请求失败',
								icon: 'none'
							})
						}
					})
					return
				}

				// 如果没有serviceTimeInfo，走原来的逻辑
				// 将选择的时间槽添加到忙碌时间
				for (const time of this.selectedTimeSlots) {
					if (!this.busyTimeSlots.includes(time)) {
						this.busyTimeSlots.push(time)
					}
				}

				// 保存到服务器
				this.saveBusyTimeSlotsToServer()

				// 清空选择的时间槽
				this.selectedTimeSlots = []

				uni.showToast({
					title: '已设置为忙时',
					icon: 'success'
				})
			},

			// 保存忙时时间段到服务器
			saveBusyTimeSlotsToServer() {
				if (!this.techId) {
					console.error('技师ID不存在')
					return
				}

				const date = this.formatFullDate(this.selectedDate)

				// 为每个选定的时间段创建请求
				const promises = this.selectedTimeSlots.map(timeSlot => {
					// 计算结束时间（当前时间+30分钟）
					const [hours, minutes] = timeSlot.split(':').map(Number)
					let endHours = hours
					let endMinutes = minutes + 30

					if (endMinutes >= 60) {
						endHours += 1
						endMinutes -= 60
					}

					// 确保时间格式正确（小时和分钟都是两位数）
					const formattedStartTime =
						`${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
					const formattedEndTime =
						`${String(endHours).padStart(2, '0')}:${String(endMinutes).padStart(2, '0')}`

					// 构建请求数据
					const data = {
						techId: this.techId,
						serviceDate: date,
						startTime: formattedStartTime, // 使用标准ISO格式 HH:mm
						endTime: formattedEndTime, // 使用标准ISO格式 HH:mm
						status: '1' // 1表示忙时状态
					}

					// 返回请求Promise
					return new Promise((resolve, reject) => {
						uni.request({
							url: `${uni.$config.baseUrl}/schedule/schedule`,
							method: 'POST',
							data: data,
							header: {
								'Content-Type': 'application/json'
							},
							success: (res) => {
								if (res.data && res.data.code === 200) {
									resolve(res)
								} else {
									reject(new Error(res.data.msg || '保存失败'))
								}
							},
							fail: (err) => {
								reject(err)
							}
						})
					})
				})

				// 处理所有请求
				Promise.all(promises)
					.then(() => {
						console.log('所有忙时时间段保存成功')
						// 重新加载时间段数据
						this.loadTimeSlots()
					})
					.catch((err) => {
						console.error('部分或全部忙时时间段保存失败:', err)
						uni.showToast({
							title: '部分时间段设置失败',
							icon: 'none'
						})
					})
			},
			showBatchSetting() {
				this.batchStartDate = new Date()
				this.batchEndDate = new Date()
				this.batchDateType = 'today'
				this.dateRowActive = 0
				this.showBatchPopup = true
			},
			cancelBatchSetting() {
				this.showBatchPopup = false
			},
			selectBatchDateType(type) {
				this.batchDateType = type
				this.selectedTimeSlots = []
				this.this.busyTimeSlots = []
				const today = new Date()
				
				switch (type) {
					case 'future24':
						// 设置为未来24小时
						this.batchStartDate = today
						this.batchEndDate = new Date(today.getTime() + 24 * 60 * 60 * 1000)
						break
					case 'today':
						// 设置为今天
						this.batchStartDate = today
						this.batchEndDate = today
						break
					case 'tomorrow':
						// 设置为明天
						const tomorrow = new Date(today)
						tomorrow.setDate(today.getDate() + 1)
						this.batchStartDate = tomorrow
						this.batchEndDate = tomorrow
						break
					case 'afterTomorrow':
						// 设置为后天
						const afterTomorrow = new Date(today)
						afterTomorrow.setDate(today.getDate() + 2)
						this.batchStartDate = afterTomorrow
						this.batchEndDate = afterTomorrow
						break
				}

				// 更新日期选项
				this.updateBatchDateOptions()
			},
			selectDateRow(index) {
				this.dateRowActive = index

				// 根据选中的行更新日期
				switch (index) {
					case 0:
						this.batchStartDate = this.batchStartDate
						break
					case 1:
						this.batchStartDate = this.getNextDay(1, this.batchStartDate)
						break
					case 2:
						this.batchStartDate = this.getNextDay(2, this.batchStartDate)
						break
				}
			},
			formatBatchDate(date) {
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${month}-${day}`
			},
			formatDateMonth(date) {
				const month = date.getMonth() + 1
				const day = date.getDate()
				const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
				return `${month}月${day}日 ${weekDay}`
			},
			getNextDay(days, baseDate = new Date()) {
				const date = new Date(baseDate)
				date.setDate(date.getDate() + days)
				return date
			},
			updateTimeSlotStatus(startTime, endTime, isBusy) {
				// 将时间转换为分钟数，方便比较
				const getMinutes = (timeStr) => {
					const [hours, minutes] = timeStr.split(':').map(Number)
					return hours * 60 + minutes
				}

				const startMinutes = getMinutes(startTime)
				const endMinutes = getMinutes(endTime)

				// 遍历所有时间槽，更新状态
				this.timeSlots.forEach(slot => {
					const slotMinutes = getMinutes(slot)
					if (slotMinutes >= startMinutes && slotMinutes <= endMinutes) {
						if (isBusy) {
							// 如果设置为忙时，添加到忙时列表
							if (!this.busyTimeSlots.includes(slot)) {
								this.busyTimeSlots.push(slot)
							}
							// 从已选择列表中移除
							const index = this.selectedTimeSlots.indexOf(slot)
							if (index > -1) {
								this.selectedTimeSlots.splice(index, 1)
							}
						} else {
							// 如果设置为可约，从忙时列表中移除
							const index = this.busyTimeSlots.indexOf(slot)
							if (index > -1) {
								this.busyTimeSlots.splice(index, 1)
							}
						}
					}
				})
			},
			setBatchAvailable() {
				this.updateTimeSlotStatus(this.batchStartTime, this.batchEndTime, false)
				// 保存批量设置到服务器
				this.saveBatchTimeToServer(this.batchStartTime, this.batchEndTime, false)

				uni.showToast({
					title: '已设置为可约',
					icon: 'success'
				})
				this.showBatchPopup = false
			},
			setBatchBusy() {
				this.updateTimeSlotStatus(this.batchStartTime, this.batchEndTime, true)
				// 保存批量设置到服务器
				this.saveBatchTimeToServer(this.batchStartTime, this.batchEndTime, true)

				uni.showToast({
					title: '已设置为忙时',
					icon: 'success'
				})
				this.showBatchPopup = false
			},
			// 保存批量设置时间到服务器
			saveBatchTimeToServer(startTime, endTime, isBusy) {
				if (!this.techId) {
					console.error('技师ID不存在')
					return
				}

				// 确保时间格式正确
				const [startHour, startMinute] = startTime.split(':').map(Number)
				const [endHour, endMinute] = endTime.split(':').map(Number)

				const formattedStartTime = `${String(startHour).padStart(2, '0')}:${String(startMinute).padStart(2, '0')}`
				const formattedEndTime = `${String(endHour).padStart(2, '0')}:${String(endMinute).padStart(2, '0')}`

				// 构建开始和结束日期
				let startDate, endDate

				switch (this.batchDateType) {
					case 'future24':
						startDate = this.formatFullDate(this.batchStartDate)
						endDate = this.formatFullDate(this.batchEndDate)
						break
					case 'today':
						startDate = this.formatFullDate(new Date())
						endDate = startDate
						break
					case 'tomorrow':
						startDate = this.formatFullDate(this.getNextDay(1))
						endDate = startDate
						break
					case 'afterTomorrow':
						startDate = this.formatFullDate(this.getNextDay(2))
						endDate = startDate
						break
					default:
						startDate = this.formatFullDate(this.batchStartDate)
						endDate = startDate
				}

				// 构建请求数据
				const requestData = {
					techId: this.techId,
					startDate: this.formatFullDate(this.batchStartDate),
					endDate: this.formatFullDate(this.batchEndDate),
					startTime: formattedStartTime,
					endTime: formattedEndTime,
					status: isBusy ? 1 : 0 // 1-忙时，0-可约
				}

				// 发送批量设置请求
				uni.request({
					url: `${uni.$config.baseUrl}/servicetime/servicetime/batchSet`,
					method: 'POST',
					data: requestData,
					header: {
						'Content-Type': 'application/json'
					},
					success: (res) => {
						if (res.data && res.data.code === 200) {
							console.log('批量设置成功:', res.data.msg)
							// 重新加载时间段数据
							this.loadTimeSlots()

							uni.showToast({
								title: '设置成功',
								icon: 'success'
							})
						} else {
							console.error('批量设置失败:', res.data.msg)
							uni.showToast({
								title: res.data.msg || '设置失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('批量设置请求失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},
			onBatchStartTimeChange(e) {
				const time = e.detail.value
				this.batchStartTime = time
			},
			onBatchEndTimeChange(e) {
				const time = e.detail.value
				this.batchEndTime = time
			},
			isPastTime(time) {
				// 只有当选择的是今天时才需要判断
				if (!this.isDateSelected(new Date())) {
					return false
				}

				const now = new Date()
				const currentHour = now.getHours()
				const currentMinute = now.getMinutes()

				// 将时间字符串转换为小时和分钟
				const [timeHour, timeMinute] = time.split(':').map(Number)

				// 比较时间
				return (timeHour < currentHour) ||
					(timeHour === currentHour && timeMinute <= currentMinute)
			},
			// 显示开始时间选择弹窗
			showStartTimeSelect() {
				// 初始化日期选项
				this.updateBatchDateOptions()

				// 初始化临时时间为当前批量设置时间
				this.tempBatchStartDate = new Date(this.batchStartDate)
				this.tempBatchStartTime = this.batchStartTime

				// 设置时间选择器的值
				this.setBatchTimePickerValue(this.batchStartTime, 'start')

				// 显示开始时间选择弹窗
				this.showBatchStartPopup = true
			},

			// 显示结束时间选择弹窗
			showEndTimeSelect() {
				// 初始化日期选项
				this.updateBatchDateOptions()

				// 初始化临时时间为当前批量设置时间
				this.tempBatchEndDate = new Date(this.batchEndDate)
				this.tempBatchEndTime = this.batchEndTime

				// 设置时间选择器的值
				this.setBatchTimePickerValue(this.batchEndTime, 'end')

				// 显示结束时间选择弹窗
				this.showBatchEndPopup = true
			},

			// 更新批量日期选项
			updateBatchDateOptions() {
				const today = new Date()
				this.batchDateOptions = Array.from({
					length: 15
				}, (_, index) => {
					const date = new Date(today)
					date.setDate(today.getDate() + index)

					let text = index === 0 ? '今天' :
						index === 1 ? '明天' :
						index === 2 ? '后天' :
						this.formatDateMonth(date)

					return {
						text,
						date
					}
				})
			},

			// 设置批量时间选择器的值
			setBatchTimePickerValue(timeStr, type) {
				const [hours, minutes] = timeStr.split(':').map(Number)

				// 找到小时在hours数组中的索引
				const hourIndex = Math.max(0, Math.min(this.hours.length - 1, hours - 8))

				// 找到分钟在halfHourMinutes数组中的索引
				const minuteIndex = minutes < 15 ? 0 : (minutes < 45 ? 1 : 0)

				if (type === 'start') {
					this.batchStartTimePickerValue = [hourIndex, 0, minuteIndex]
				} else {
					this.batchEndTimePickerValue = [hourIndex, 0, minuteIndex]
				}
			},

			// 取消批量时间选择
			cancelBatchTimeSelect() {
				this.showBatchStartPopup = false
				this.showBatchEndPopup = false
			},

			// 确认批量开始时间选择
			confirmBatchStartTimeSelect() {
				// 更新批量开始日期和时间
				this.batchStartDate = this.tempBatchStartDate
				this.batchStartTime = this.tempBatchStartTime

				// 检查结束时间是否小于开始时间
				if (this.isEndTimeBeforeStartTime()) {
					// 如果结束时间小于开始时间，自动调整结束时间
					this.batchEndDate = new Date(this.batchStartDate)
					this.batchEndTime = this.batchStartTime
				}

				// 关闭弹窗
				this.showBatchStartPopup = false
			},

			// 确认批量结束时间选择
			confirmBatchEndTimeSelect() {
				// 检查结束时间是否小于开始时间
				if (this.isEndTimeBeforeStartTime()) {
					uni.showToast({
						title: '结束时间必须大于开始时间',
						icon: 'none'
					})
					return
				}

				// 更新批量结束日期和时间
				this.batchEndDate = this.tempBatchEndDate
				this.batchEndTime = this.tempBatchEndTime

				// 关闭弹窗
				this.showBatchEndPopup = false
			},

			// 检查结束时间是否小于开始时间
			isEndTimeBeforeStartTime() {
				// 将日期和时间转换为时间戳进行比较
				const startDate = new Date(this.tempBatchStartDate)
				const endDate = new Date(this.tempBatchEndDate)

				// 设置时间部分
				const [startHour, startMinute] = this.tempBatchStartTime.split(':').map(Number)
				const [endHour, endMinute] = this.tempBatchEndTime.split(':').map(Number)

				startDate.setHours(startHour, startMinute, 0, 0)
				endDate.setHours(endHour, endMinute, 0, 0)

				return endDate <= startDate
			},

			// 选择批量日期
			selectBatchDate(date, type) {
				if (type === 'start') {
					this.tempBatchStartDate = new Date(date)
					// 如果结束日期小于开始日期，自动调整结束日期
					if (this.tempBatchEndDate < this.tempBatchStartDate) {
						this.tempBatchEndDate = new Date(this.tempBatchStartDate)
					}
				} else {
					// 检查选择的结束日期是否小于开始日期
					if (date < this.tempBatchStartDate) {
						uni.showToast({
							title: '结束日期必须大于开始日期',
							icon: 'none'
						})
						return
					}
					this.tempBatchEndDate = new Date(date)
				}
			},

			// 判断批量日期是否被选中
			isBatchDateSelected(date) {
				if (this.showBatchStartPopup) {
					return this.formatDate(date) === this.formatDate(this.tempBatchStartDate)
				} else if (this.showBatchEndPopup) {
					return this.formatDate(date) === this.formatDate(this.tempBatchEndDate)
				}
				return false
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 0 0 100rpx;
		/* 为顶部标题和底部导航栏留出空间 */
	}

	.date-scroll {
		background: #FFFFFF;
		white-space: nowrap;
		padding: 20rpx 0;

		.date-list {
			display: inline-flex;
			padding: 0 20rpx;

			.date-item {
				padding: 10rpx 30rpx;
				margin-right: 20rpx;
				border-radius: 8rpx;
				background: #F8F8F8;
				text-align: center;

				&.active {
					background: #2B85E4;

					.date-code,
					.date-text {
						color: #FFFFFF;
					}
				}

				.date-code {
					font-size: 32rpx;
					color: #333;
					margin-bottom: 4rpx;
					display: block;
				}

				.date-text {
					font-size: 28rpx;
					color: #666;
				}
			}
		}
	}

	.service-time {
		margin: 20rpx;
		background: #FFFFFF;
		border-radius: 12rpx;
		padding: 20rpx;

		.time-header {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
			font-size: 32rpx;
			color: #333;

			.time-range {
				color: #2B85E4;
				margin: 0 10rpx;
			}

			.modify {
				color: #2B85E4;
			}

			.batch-setting-btn {
				color: #2B85E4;
				margin-left: auto;
			}
		}

		.time-grid {
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 20rpx;

			.time-item {
				background: #F8F8F8;
				border-radius: 8rpx;
				padding: 20rpx 0;
				text-align: center;
				position: relative;

				&.rest {
					background: #F0F0F0 !important;
					cursor: not-allowed !important;
					opacity: 0.7 !important;

					.time,
					.status {
						color: #999 !important;
					}
				}

				&.selected {
					background: rgba(43, 133, 228, 0.1);

					.time,
					.status {
						color: #2B85E4;
					}
				}

				&.busy {
					background: rgba(43, 133, 228, 0.1);

					.time,
					.status {
						color: #2B85E4;
					}
				}

				&.past {
					background: #F0F0F0;
					cursor: not-allowed;
					opacity: 0.7;

					&:after {
						content: "";
						position: absolute;
						top: 0;
						left: 0;
						right: 0;
						bottom: 0;
						background: rgba(255, 255, 255, 0.2);
					}

					.time,
					.status {
						color: #999;
					}
				}

				.time {
					font-size: 32rpx;
					color: #333;
					margin-bottom: 4rpx;
					display: block;
				}

				.status {
					font-size: 28rpx;
					color: #666;
				}
			}
		}
	}

	.custom-popup {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 999;

		.popup-mask {
			position: absolute;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			background-color: rgba(0, 0, 0, 0.4);
		}

		.popup-content {
			position: absolute;
			left: 0;
			bottom: 0;
			width: 100%;
			transform: translate3d(0, 0, 0);
			transition: all 0.3s;
		}
	}

	.time-popup {
		background: #FFFFFF;
		border-radius: 24rpx 24rpx 0 0;
		overflow: hidden;
		position: relative;
		padding: 60rpx 30rpx 40rpx;

		.close-icon {
			position: absolute;
			right: 30rpx;
			top: 30rpx;
			font-size: 54rpx;
			color: #999;
			z-index: 10;
		}

		.time-selector {
			display: flex;
			justify-content: space-around;
			padding: 20rpx 0;
		}

		.time-picker-view {
			width: 220rpx;
			height: 300rpx;
			text-align: center;

			.picker-item {
				line-height: 100rpx;
				text-align: center;
				font-size: 64rpx;
				color: #333;
			}

			.picker-separator {
				line-height: 100rpx;
				text-align: center;
				font-size: 64rpx;
				color: #2B85E4;
			}
		}

		.confirm-btn {
			margin: 40rpx auto 0;
			height: 88rpx;
			line-height: 88rpx;
			background: #2B85E4;
			color: #FFFFFF;
			font-size: 36rpx;
			text-align: center;
			border-radius: 44rpx;
		}
	}

	.save-button-container {
		position: fixed;
		bottom: 200rpx;
		left: 0;
		right: 0;
		padding: 0 30rpx;
	}

	.save-button {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		background: linear-gradient(to right, #5677fc, #5c8dfe);
		color: #fff;
		font-size: 36rpx;
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 批量设置相关样式 */
	.batch-popup {
		background: #FFFFFF;
		border-radius: 24rpx 24rpx 0 0;
		overflow: hidden;
		padding: 30rpx;
	}

	.batch-popup-title {
		font-size: 40rpx;
		font-weight: bold;
		text-align: center;
		position: relative;
		margin-bottom: 30rpx;
	}

	.time-range-display {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 30rpx 0;
	}

	.time-input {
		background: #F5F5F5;
		border-radius: 8rpx;
		padding: 20rpx 30rpx;
		font-size: 34rpx;
		color: #333;
		text-align: center;
		flex: 1;
	}

	.time-separator {
		margin: 0 20rpx;
		font-size: 40rpx;
		color: #333;
	}

	.date-buttons {
		display: flex;
		justify-content: space-between;
		margin-bottom: 30rpx;
	}

	.date-button {
		background: #F5F5F5;
		border-radius: 8rpx;
		padding: 15rpx 10rpx;
		font-size: 32rpx;
		color: #333;
		text-align: center;
		flex: 1;
		margin: 0 10rpx;
	}

	.date-button.active {
		background: #2B85E4;
		color: #FFFFFF;
	}

	.date-time-pickers {
		margin: 20rpx 0 40rpx;
		border-top: 1px solid #EEEEEE;
		border-bottom: 1px solid #EEEEEE;
	}

	.date-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 25rpx 20rpx;
		border-bottom: 1px solid #EEEEEE;

		&:last-child {
			border-bottom: none;
		}

		&.active {
			background: #F0F9FF;

			.date-text,
			.time-text {
				color: #2B85E4;
			}
		}

		.date-text {
			font-size: 34rpx;
			color: #333;
		}
	}

	.time-select {
		display: flex;
		align-items: center;
		gap: 10rpx;

		.time-text {
			font-size: 34rpx;
			color: #333;
			background: #F5F5F5;
			padding: 4rpx 16rpx;
			border-radius: 4rpx;
		}

		.separator {
			font-size: 28rpx;
			color: #666;
		}
	}

	.batch-action-buttons {
		display: flex;
		justify-content: space-between;
	}

	.batch-action-btn {
		flex: 1;
		height: 88rpx;
		line-height: 88rpx;
		text-align: center;
		font-size: 36rpx;
		border-radius: 8rpx;
		margin: 0 10rpx;
	}

	.batch-action-btn.available {
		background: #4CD964;
		color: #FFFFFF;
	}

	.batch-action-btn.busy {
		background: #2B85E4;
		color: #FFFFFF;
	}

	/* 批量设置时间选择器样式 */
	.date-selector {
		display: block;
		padding: 20rpx 0;
		border-bottom: 1px solid #EEEEEE;
		margin-bottom: 20rpx;
		max-height: 400rpx;

		.date-row {
			padding: 20rpx 30rpx;
			margin: 10rpx 20rpx;
			border-radius: 8rpx;
			background: #F8F8F8;
			text-align: center;

			&.active {
				background: #2B85E4;

				.date-code,
				.date-text {
					color: #FFFFFF;
				}
			}

			.date-code {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 4rpx;
				display: block;
			}

			.date-text {
				font-size: 28rpx;
				color: #666;
			}
		}
	}
</style>